package com.alex.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 服务降级Filter
 *
 * @author Alex.shu
 */
public class DownGradeFilter extends ZuulFilter {

    @Autowired
    private BasicConfig basicConfig;

    public DownGradeFilter() {
        super();
    }

    @Override
    public String filterType() {
        return "route";
    }

    @Override
    public int filterOrder() {
        return 4;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        Object isSuccess = currentContext.get("isSuccess");
        return Objects.isNull(isSuccess) || Boolean.parseBoolean(isSuccess.toString());
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        Object serviceId = currentContext.get("serviceId");
        if (Objects.nonNull(serviceId) && Objects.nonNull(basicConfig)) {
            List<String> serviceIds = Arrays.asList(basicConfig.getDownGradeStr().split(","));
            if (serviceIds.contains(serviceId.toString())) {
                currentContext.setSendZuulResponse(false);
                currentContext.set("isSuccess", false);

                currentContext.setResponseBody("服务降级中: " + serviceId);
                currentContext.getResponse().setContentType("application/json; charset=utf-8");

                return null;
            }
        }

        return null;
    }
}
